const bcrypt = require('bcryptjs');
const UserModel = require('../user.model');

/**
 * User Service V1
 * Legacy service methods with old business logic
 * @deprecated Use V2 service instead
 */
class UserServiceV1 {
  /**
   * Get all users (V1 format)
   */
  static async getAllUsers() {
    // 使用共享的 Model 进行数据查询
    const result = await UserModel.findAll();
    
    // V1 特定的数据格式化（简单格式）
    return result.data.map(user => ({
      id: user.id,
      username: user.username,
      email: user.email,
      created_at: user.created_at,
      updated_at: user.updated_at
    }));
  }

  /**
   * Get user by ID (V1 format)
   */
  static async getUserById(id) {
    const user = await UserModel.findById(id);
    
    if (!user) return null;
    
    // V1 format: simple flat structure
    return {
      id: user.id,
      username: user.username,
      email: user.email,
      created_at: user.created_at,
      updated_at: user.updated_at
    };
  }

  /**
   * Create user (V1 logic)
   */
  static async createUser(userData) {
    const { username, email, password } = userData;
    
    // V1 simple password hashing
    const hashedPassword = await bcrypt.hash(password, 10);
    
    const newUser = await UserModel.create({
      username,
      email,
      password_hash: hashedPassword, // 修复：使用正确的数据库字段名
      role: 'user' // V1 默认角色
    });
    
    // V1 format: return simple structure
    return {
      id: newUser.id,
      username: newUser.username,
      email: newUser.email,
      created_at: newUser.created_at
    };
  }
}

module.exports = UserServiceV1;